<template>
  <div class="request-party-service-manage">
    <div class="app-container">
      <div class="mainbox">
        <Header :header-name="$route.meta.title" />

        <div class="request-party-service-manage-body">

          <!-- 搜索板块 -->
          <el-form ref="form" :model="form" inline label-width="80px" class="search-form">
            <el-form-item prop="dataSourceName">
              <el-input v-model="form.dataSourceName" clearable placeholder="数据源名称" />
            </el-form-item>
            <el-form-item prop="dataSourceType">
              <el-select v-model="form.dataSourceType" placeholder="所有数据源" clearable filterable>
                <el-option value="mysql" label="mysql数据库" />
                <el-option value="oracle" label="oracle数据库" />
                <el-option value="pgsql" label="pgsql数据库" />
                <el-option value="mssql" label="sqlServer数据库" />
                <el-option value="dm" label="dm数据库" />
              </el-select>
            </el-form-item>
            <el-form-item prop="systemId">
              <el-select v-model="form.systemId" placeholder="系统名称" clearable filterable>
                <el-option
                  v-for="(item, index) in systemIdList"
                  :key="index"
                  :label="item.systemCode + ' / ' + item.systemName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item class="query-action">
              <el-dropdown trigger="click" style="margin-right: 10px;">
                <el-button class="el-dropdown-link">
                  导出<i class="el-icon-arrow-down el-icon--right" />
                </el-button>
                <el-dropdown-menu slot="dropdown" style="width:100px;text-align:center">
                  <el-dropdown-item @click.native="handleDownload('all')"> 导出所有 </el-dropdown-item>
                  <el-dropdown-item @click.native="handleDownload()"> 导出选中 </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-button @click="handleImport">导入</el-button>
              <el-button :loading="loading" @click="resetBtn"> 重置 </el-button>
              <el-button type="primary" @click="getTableData"> 查询 </el-button>
              <el-button v-permission="['DATASOURCESTATUSMONITORING_ADD_BUTTON']" type="primary" @click="addBtn"> 新增 </el-button>
              <!--              <el-button v-permission="['DATASOURCESTATUSMONITORING_DEL_BUTTON']" :disabled="multipleSelection.length === 0" type="danger" @click="delBtn"> 删除 </el-button>-->
            </el-form-item>
          </el-form>

          <!-- 表格数据视图 -->
          <div>
            <FlexTable
              v-loading="loading"
              border
              :data="tableData"
              :columns="columnsOptions"
              @selection-change="handleSelectionChange"
            />

            <el-pagination
              :page-size="pagination.pageSize"
              :current-page.sync="pagination.pageNo"
              layout="prev, pager, next, jumper"
              :total="pagination.totalPage"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>

        <!-- 添加或修改接口服务监测对话框 -->
        <DataAddDialog
          ref="DataAddDialogRef"
          :receive-user-list="receiveUserList"
          :system-id-list="systemIdList"
          @getList="getTableData"
          @changeType="changeType"
        />
        <monitor-log ref="monitorLog" />
        <dtDialog
          title="导入"
          class="request-party-service-manage-import-dialog"
          :visible.sync="fileUploadVisible"
          width="620px"
          :is-loading="uploadLoading"
          @closeDialog="fileUploadVisible = false"
          @comfirmBtn="importDataSave"
        >
          <el-form slot="content">
            <div class="">
              <dt-importFile ref="dtImportFileRef" :down-load-template="handleImportTemplate" :type="fileName" />
            </div>
          </el-form>
        </dtDialog>
      </div>
    </div>
  </div>
</template>

<script>
import databaseMonitorApi from '@/api/monitor/DatabaseMonitor'
import MonitorLog from '@/views/serviceMonitor/monitorLog.vue'
import DataAddDialog from '@/views/dataSourceStatusMonitoring/components/dataAddDialog.vue'
import { getSystemListApi } from '@/api/serviceManage/requestPartyServiceManage'
import { editRes } from '@/utils/editAlarmUser'
import { listMonitorAlarmUser } from '@/api/contactAlarm'
import { changeTaskStatus, downloadTemplateApi, exportAll, partExport, uploadApi } from '@/api/serviceWatch'

export default {
  name: 'DataSourceStatusMonitoring',
  components: {
    MonitorLog,
    DataAddDialog
  },
  data () {
    return {
      multipleSelection: [],
      fileName: '数据源状态监控导入',
      handleImportTemplate: downloadTemplateApi,
      fileUploadVisible: false,
      uploadLoading: false,
      // 弹出层标题
      title: '',
      operate: 'add',
      // 是否显示弹出层
      showDetail: true,
      form: {},
      loading: false,
      tableData: [],
      systemIdList: [],
      receiveUserList: [],
      columnsOptions: [
        { type: 'selection' },
        { label: '数据源名称', prop: 'dataSourceName' },
        { label: '数据源类型', prop: 'dataSourceType' },
        { label: '系统名称', prop: 'systemName' },
        { label: '数据源IP', prop: 'jdbcIp' },
        { label: '创建时间', prop: 'createTime' },
        { label: '创建人', prop: 'createUserName' },
        { label: '当前状态', prop: 'status' },
        { label: '状态更新时间', prop: 'updateTime' },
        { label: '备注', prop: 'remarks' },
        { label: '操作', width: 200,
          customRender: (scope) => {
            return [
              <el-button vPermission={['SYSTEMMANAGE_TASKSTATUS_BUTTON']} type='text' onClick={() => this.changeType(scope.row)}> {scope.row.taskStatus === '1' ? '停止' : '启用'} </el-button>,
              <el-button vPermission={['SYSTEMMANAGE_CONNECT_BUTTON']} type='text' onClick={() => this.show(scope.row)}> 连接详情 </el-button>,
              <el-button vPermission={['DATASOURCESTATUSMONITORING_UPDATE_BUTTON']} type='text' onClick={() => this.edit(scope.row)}> 编辑 </el-button>,
              <el-button vPermission={['DATASOURCESTATUSMONITORING_DEL_BUTTON']} type='text' class='text-del-btn' onClick={() => this.delBtn(scope.row)}> 删除 </el-button>
            ]
          }
        }
      ],
      pagination: {
        pageNo: 1,
        pageSize: 10,
        totalPage: null
      }

    }
  },
  created() {
    this.infoData()
    this.getTableData()
    listMonitorAlarmUser({ pageNo: 1, pageSize: -1 }).then(res => {
      this.receiveUserList = res.data.rows
    })
  },
  methods: {
    handleDownload(type) {
      let con = {}
      if (type == 'all') {
        this.showScreenLoading()
        exportAll().then(res => {
          const blob = new Blob([res.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
          const objectUrl = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.style.display = 'none'
          a.href = objectUrl // 指定下载链接
          a.download = '数据源状态监控全部导出' // 指定下载文件名
          a.click()
          URL.revokeObjectURL(a.href) // 释放URL对象
          this.hideScreenLoading()
        }).catch(res => {
          this.hideScreenLoading()
        })
      } else {
        if (!this.multipleSelection || this.multipleSelection.length === 0) {
          this.$dtMessage({
            title: '失败',
            message: '请至少选择一项',
            type: 'error',
            duration: 2000
          })
          return
        }
        const ids = this.multipleSelection.map(res => {
          return res.id
        }).join(',')
        con = {
          dataMonitorIds: ids
        }
        this.showScreenLoading()
        partExport(con).then(res => {
          const blob = new Blob([res.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
          const objectUrl = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.style.display = 'none'
          a.href = objectUrl // 指定下载链接
          a.download = '数据源状态监控部分导出' // 指定下载文件名
          a.click()
          URL.revokeObjectURL(a.href) // 释放URL对象
          this.hideScreenLoading()
        }).catch(res => {
          this.hideScreenLoading()
        })
      }
    },
    async handleImport() {
      this.fileUploadVisible = true
      await this.$nextTick()
      this.$refs.dtImportFileRef.fileList = []
    },
    changeType(val) {
      const data = {
        ids: [val.id],
        type: '1',
        taskStatus: val.taskStatus === '1' ? '2' : '1'
      }
      changeTaskStatus(data).then(res => {
        if (res.data === true) {
          this.$message.success(data.taskStatus === '1' ? '启用成功' : '停用成功')
          this.getTableData()
        } else {
          this.$message.success(data.taskStatus === '1' ? '启用失败' : '停用失败')
        }
      })
    },
    infoData() {
      getSystemListApi()
        .then(({ code, data }) => {
          if (code === '00000') {
            this.systemIdList = data
          }
        })
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.pagination.pageNo = val
      this.getTableData()
    },
    getTableData() {
      this.setLoading(true)
      const params = {
        pageNo: this.pagination.pageNo,
        pageSize: this.pagination.pageSize,
        ...this.form
      }
      databaseMonitorApi.listDatabaseMonitor(params).then(res => {
        const { code, data } = res
        if (code === '00000') {
          this.tableData = data.rows
          this.pagination.totalPage = data.totalRows
        } else {
          this.showMessage('error', '无法获取表单数据')
        }
      }).finally(() => {
        this.setLoading(false)
      })
    },
    resetBtn() {
      this.form = {}
      Object.assign(this.pagination, {
        pageNo: 1,
        pageSize: 10,
        totalPage: 0
      })
      this.getTableData()
    },

    async addBtn() {
      this.$refs.DataAddDialogRef.open = true
      this.$refs.DataAddDialogRef.title = '新增数据源信息'
      await this.$nextTick()
      this.$refs.DataAddDialogRef.$refs.formRef.clearValidate()
    },
    show(detail) {
      // this.row=detail;
      // this.open=true;
      // this.title="数据源信息详情";
      // this.operate='detail';
      // this.showDetail=false;
      this.$refs.monitorLog.init(detail.id, 1, detail.dataSourceName, detail.jdbcIp)
    },
    edit(detail) {
      databaseMonitorApi.getDatabaseMonitor(detail.id).then(res => {
        this.$refs.DataAddDialogRef.row = res.data
        this.$refs.DataAddDialogRef.row.alarmUsers = editRes(res.data.alarmUsers)
        this.$refs.DataAddDialogRef.open = true
        this.$refs.DataAddDialogRef.title = '修改数据源信息'
      })
    },
    delBtn(detail) {
      this.$confirm('此操作将删除数据源, 是否删除?', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // const ids = detail.id ? [detail.id] : this.multipleSelection.map(item => item.id)
        databaseMonitorApi.deleteById(detail).then(res => {
          this.$message.success('删除成功')
          this.getTableData()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 多选框选中数据
    handleSelectionChange(val) {
      this.multipleSelection = []
      this.multipleSelection = val
    },
    setLoading(loading) {
      this.loading = loading
    },
    importDataSave() {
      const file = this.$refs.dtImportFileRef.fileList
      if (file.length == 0) {
        this.$dtMessage({
          title: '失败',
          message: '请选择需要上传的文件',
          type: 'error',
          duration: 2000
        })
        return
      }
      const formData = new FormData()
      // 数据
      formData.append('file', file[0].raw)
      formData.append('name', file[0].name)
      this.uploadLoading = true
      uploadApi(formData).then(async(res) => {
        this.fileUploadVisible = false
        if (res.errorDownloadPath) {
          this.$alert('<div> <div class="title">' + res.tip + '</div> <div class="content"><span class="btn" id="messageBtn" style="color:#5688E8;cursor:pointer">点击下载导入失败用户信息</span> </div> </div>', '导入完成', {
            dangerouslyUseHTMLString: true
          })
        } else {
          this.$alert('<div> <div class="title">' + res.tip + '导入完成', {
            dangerouslyUseHTMLString: true
          })
        }
        // this.$message.success('导入成功')
        this.getTableData()
        await this.$nextTick()
        document.getElementById('messageBtn').onclick = function() {
          window.location.href = res.errorDownloadPath
        }
      }).finally(res => {
        this.uploadLoading = false
      })
    }

  }
}
</script>
<style lang="scss" scoped>
.request-party-service-manage {
  background: #F2F2F2;

  &-body {
    background: #fff;
    margin-top: 10px;
    padding: 20px;
    height: calc(100vh - 254px);
    overflow-y: auto;
  }
  .el-pagination {
    text-align: right;
    margin-top: 20px;
  }

  .el-tree {
    ::v-deep .el-tree-node__expand-icon {
      font-size: 18px;
    }
    .custom-tree-node {
      width: calc(100% - 30px);
      display: flex;
      align-items: center;
      padding-right: 20px;

      > span:first-child {
        display: inline-block;
        width: calc(100% - 50px);
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        line-height: 40px;
      }

      .tree-btn {
        .el-switch {
          margin-top: -4px;
          margin-left: 10px;
        }
      }
    }
  }
}
::v-deep.request-party-service-manage-import-dialog {
  .el-upload-list__item {
    transition: none !important;
  }
  .el-upload-list__item-name {
    transition: none !important;
  }
}
</style>

